package com.zretc.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.zretc.entity.*;
import com.zretc.service.AddressInfoService;
import com.zretc.service.OrderService;
import com.zretc.util.AlipayConfig;
import com.zretc.util.Util;
import org.apache.http.HttpResponse;
import org.omg.IOP.IOR;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * @author: bLUeSuMMerDreamer
 * @createTime: 2020-07-24 20:00
 */
@Controller
@RequestMapping("/order")
public class OrderController {
    private static Logger logger = LoggerFactory.getLogger(OrderController.class);
    @Autowired
    private OrderService orderService;
    @Autowired
    private AddressInfoService addressInfoService;


    /**
     * @param :cost
     * @param :orderComment
     * @param :receiveAdCode
     * @param :receiveAddressDetail
     * @param :receiveCity
     * @param :receiveCompanyName
     * @param :receiveDistrict
     * @param :receiveLat
     * @param :receiveLng
     * @param :receiveName
     * @param :receivePhone
     * @param :receiveProvince
     * @param :sendAdCode
     * @param :sendAddressDetail
     * @param :sendCity
     * @param :sendCompanyName
     * @param :sendDistrict
     * @param :sendLat
     * @param :sendLng
     * @param :sendName
     * @param :sendPhone
     * @param :sendProvince
     * @param :typeSelect
     * @param :weight
     * @author: bLUeSuMMerDreamer
     * @date: 2020/7/24 20:19
     * @return: java.lang.Boolean
     */
    @RequestMapping(value = "/addOrder")
    //@ResponseBody
    public void addOrder(HttpServletRequest request, HttpServletResponse response, String receiveAddressInfoId, String sendAddressInfoId, Double cost, String orderComment, String receiveAdCode, String receiveAddressDetail, String receiveCity, String receiveCityCode, String receiveCompanyName, String receiveDistrict, Double receiveLat, Double receiveLng, String receiveName, String receivePhone, String receiveProvince, String sendAdCode, String sendAddressDetail, String sendCity, String sendCityCode, String sendCompanyName, String sendDistrict, Double sendLat, Double sendLng, String sendName, String sendPhone, String sendProvince, String typeSelect, Double weight, String endHouseId) throws IOException, AlipayApiException {
        //寄件详细地址
        String sendAddressName = (sendProvince + " " + sendCity + " " + sendDistrict + " " + sendAddressDetail + " " + sendCompanyName).trim();
        //收件详细地址拼接
        String receiveAddressName = (receiveProvince + " " + receiveCity + " " + receiveDistrict + " " + receiveAddressDetail + " " + receiveCompanyName).trim();
        //寄件地址信息 Address
        //寄件地址簿类 AddressInfo
        AddressInfo sendAddressInfo = getAddressInfo(sendAddressInfoId, sendAdCode, sendCity, sendCityCode, sendDistrict, sendLat, sendLng, sendName, sendPhone, sendProvince, sendAddressName);
        //收件地址信息 Address
        //收件地址簿类 AddressInfo
        AddressInfo receiveAddressInfo = getAddressInfo(receiveAddressInfoId, receiveAdCode, receiveCity, receiveCityCode, receiveDistrict, receiveLat, receiveLng, receiveName, receivePhone, receiveProvince, receiveAddressName);
        //生成新的orderId
        String orderId = Util.getOrderId();
        Type type = new Type();
        type.setTypeId(typeSelect);
        House house = new House();
        house.setHouseId(endHouseId);
        Order order = new Order(orderId, cost, type, weight, receiveAddressInfo, sendAddressInfo, orderComment, 0, house, null);
        if (orderService.addOrder2(order)) {
            goToAliPay(request, response, order);
            //return new ResponseEntity(order, HttpStatus.OK);
            //return true;
        } else {
            //return new ResponseEntity(null, HttpStatus.NO_CONTENT);
            //return false;
            PrintWriter out = response.getWriter();
            out.println(false);
        }
        //return false;
        //return orderService.addOrder2(order);
        //return true;
    }

    @RequestMapping(value = "/payOrder")
    public void payOrder(@RequestParam(value = "orderId") String orderId, @RequestParam(value = "cost") Double cost, HttpServletResponse response, HttpServletRequest request) throws IOException, AlipayApiException {
        Order order = new Order();
        order.setOrderId(orderId);
        order.setCost(cost);
        goToAliPay(request, response, order);
    }

    /**
     * 根据订单构建支付宝交易信息并跳转页面
     *
     * @param :request
     * @param :response
     * @param :order
     * @author: bLUeSuMMerDreamer
     * @date: 2020/7/26 3:31
     * @return: void
     */
    private void goToAliPay(HttpServletRequest request, HttpServletResponse response, Order order) throws AlipayApiException, IOException {
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
        alipayRequest.setBizContent("{\"out_trade_no\":\"" + order.getOrderId() + "\"," +
                "\"total_amount\":\"" + order.getCost() + "\"," +
                "\"subject\":\"码上物流寄件服务\"," +
                //"\"body\":\"激素的\"," +
                "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"" +
                //"\"goods_detail\":{\"goods_id\":\"" + order.getOrderId() + "\"  ,\"goods_name\":\"码上物流寄件服务\",\"quantity\":\"1\",\"price\":\"" + order.getCost() + "\"}" +
                "}");
        // 请求"
        String result = alipayClient.pageExecute(alipayRequest).getBody();
        AlipayConfig.logResult(result);// 记录支付日志
        response.setContentType("text/html; charset=utf-8");
        PrintWriter out = response.getWriter();
        out.println(result);
    }

    /**
     * 支付完成后的回调Url
     *
     * @author: bLUeSuMMerDreamer
     * @date: 2020/7/26 3:29
     * @param: request
     * @param: response
     * @return: void
     */
    @RequestMapping(value = "/returnUrl")
    public void returnUrl(HttpServletRequest request, HttpServletResponse response) throws IOException, AlipayApiException {
        //PrintWriter out = response.getWriter();
        //获取支付宝GET过来反馈信息
        //Map<String, String> params = new HashMap<String, String>();
        //Map<String, String[]> requestParams = request.getParameterMap();
        //for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
        //    String name = (String) iter.next();
        //    String[] values = (String[]) requestParams.get(name);
        //    String valueStr = "";
        //    for (int i = 0; i < values.length; i++) {
        //        valueStr = (i == values.length - 1) ? valueStr + values[i]
        //                : valueStr + values[i] + ",";
        //    }
        //    //乱码解决，这段代码在出现乱码时使用
        //    valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
        //    params.put(name, valueStr);
        //}
        //更新订单状态
        Map<String, Object> setParam = new HashMap<>();
        setParam.put("state", 1);
        Map<String, Object> whereParam = new HashMap<>();
        whereParam.put("orderId", request.getParameter("out_trade_no"));
        orderService.updateOrderByParam(setParam, whereParam);
        //设置支付成功重定向页面
        response.sendRedirect("/front/orderSuccess.jsp?orderId=" + request.getParameter("out_trade_no"));
        //验签交易信息
        //boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名


    }

    /**
     * 构建地址簿信息
     *
     * @param :addressInfoId
     * @param :adCode
     * @param :city
     * @param :cityCode
     * @param :district
     * @param :lat
     * @param :lng
     * @param :name
     * @param :phone
     * @param :province
     * @param :addressName
     * @author: bLUeSuMMerDreamer
     * @date: 2020/7/25 21:33
     * @return: com.zretc.entity.AddressInfo
     */
    private AddressInfo getAddressInfo(String addressInfoId, String adCode, String city, String cityCode, String district, Double lat, Double lng, String name, String phone, String province, String addressName) {
        AddressInfo AddressInfo;
        if (addressInfoId != null && !"".equals(addressInfoId)) {
            //登录寄件
            //从缓存之中拿到地址信息
            AddressInfo = addressInfoService.getAddressInfoById(addressInfoId);
        } else {
            //无账户
            Address Address = new Address(Util.getUUID(), addressName, lng, lat, city, province, district, adCode, cityCode);
            AddressInfo = new AddressInfo(Util.getUUID(), Address, phone, name, null);
        }
        return AddressInfo;
    }

    @RequestMapping(value = "/getOrdersByIds", method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity getOrderById(@RequestParam(value = "orderIds") List<String> orderIds) {
        List<Order> orders = new Vector<>();
        for (String orderId : orderIds) {
            Order order = orderService.getOrderById(orderId);
            if (order != null) {
                orders.add(order);
            }
        }
        return new ResponseEntity(orders, HttpStatus.OK);
    }

    @RequestMapping(value = "/getMyOrder", method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity<List<Order>> getMyOrder(@RequestParam(value = "userPhone") String userPhone, @RequestParam(value = "isSend") Boolean isSend) {
        List<Order> orders;
        Map<String, Object> params = new HashMap<>();
        if (isSend)
            params.put("sendPhone", userPhone);
        else
            params.put("receivePhone", userPhone);
        orders = orderService.getOrderByParam(params);
        if (orders.size() != 0)
            return new ResponseEntity<>(orders, HttpStatus.OK);
        else
            return new ResponseEntity<>(null, HttpStatus.NO_CONTENT);
    }
}
